<?php
declare(strict_types=1);

namespace App\Exception\Handler;

use HKY\HyperfResponse\HttpServer\Contract\HKYResponseInterface;
use Psr\Http\Message\ResponseInterface;
use \Hyperf\Validation\ValidationExceptionHandler as V;
use Throwable;
use Hyperf\Di\Annotation\Inject;


class ValidationExceptionHandler extends V
{
    const DEFAULT_VALIDATION_ERROR_CODE = -10000;

    /**
     * @Inject
     * @var HKYResponseInterface
     */
    protected $response;


    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->stopPropagation();
        /** @var \Hyperf\Validation\ValidationException $throwable */
        $body = $throwable->validator->errors()->first();

        list($message, $code) = explode('|', $body);

        // 默认值
        !isset($message) && $message = '';
        !isset($code) && $code = self::DEFAULT_VALIDATION_ERROR_CODE;

        return $this->response->error($message, $code);
    }
}
